<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Event;

use Admin\Data\Common;
use Admin\Service\Common\PhoneMessage;
use Doctrine\ORM\EntityManager;
use Laminas\EventManager\Event;
use Laminas\EventManager\EventManagerInterface;
use Laminas\EventManager\ListenerAggregateInterface;
use Laminas\I18n\Translator\Translator;
use User\Entity\User;

class SmsListener implements ListenerAggregateInterface
{
    protected $listeners = [];

    private $translator;
    private $entityManager;

    public function __construct(
        EntityManager   $entityManager
    )
    {
        $this->translator       = new Translator();
        $this->entityManager    = $entityManager;
    }

    public function attach(EventManagerInterface $events, $priority = 1)
    {
        $shareEvents = $events->getSharedManager();

        //前台提交订单完成，发送手机短信
        $this->listeners[] = $shareEvents->attach(
            'Shop\Controller\CheckoutController', 'shop.checkout.two.post', [$this, 'onSendAddOrderSms']
        );

        //前台订单付款完成，发送手机短信
        $this->listeners[] = $shareEvents->attach(
            'Shop\Controller\NotifyController', 'shop.order.notifyPayFinish.post', [$this, 'onSendPaymentOrderSms']
        );
        //后台订单付款完成，发送手机短信
        $this->listeners[] = $shareEvents->attach(
            'Sales\Controller\IndexController', 'backstage-order.pay.post', [$this, 'onSendPaymentOrderSms']
        );

        //后台订单发货完成，发送手机短信
        $this->listeners[] = $shareEvents->attach(
            'Sales\Controller\IndexController', 'backstage-order.ship.post', [$this, 'onSendShipOrderSms']
        );

        //前台订单收货完成，发送手机短信
        $this->listeners[] = $shareEvents->attach(
            'Shop\Controller\HomeOrderController', 'shop.order.receipt.post', [$this, 'onSendReceiptOrderSms']
        );
        //后台订单收货完成，发送手机短信
        $this->listeners[] = $shareEvents->attach(
            'Sales\Controller\IndexController', 'backstage-order.receipt.post', [$this, 'onSendReceiptOrderSms']
        );

        //前台订单取消完成，发送手机短信
        $this->listeners[] = $shareEvents->attach(
            'Shop\Controller\HomeOrderController', 'shop.order.cancel.post', [$this, 'onSendCancelOrderSms']
        );
        //后台订单取消完成，发送手机短信
        $this->listeners[] = $shareEvents->attach(
            'Sales\Controller\IndexController', 'backstage-order.cancel.post', [$this, 'onSendCancelOrderSms']
        );
    }

    public function detach(EventManagerInterface $events)
    {
        foreach ($this->listeners as $index => $listener) {
            $events->detach($listener);
            unset($this->listeners[$index]);
        }
    }

    /**
     * 前台提交订单完成，发送手机短信
     * @param Event $event
     * @return bool
     */
    public function onSendAddOrderSms(Event $event)
    {
        $data = $this->checkSendSms($event);
        if(!$data) return false;

        $sendArray  = $data['sendArray'];

        return PhoneMessage::sendOrderSms(['phoneAreaCode' => $data['userInfo']->getAreaCode(), 'phone' => $data['userInfo']->getUserPhone(), 'contentArray' => $sendArray, 'templateCode' => 'addOrder']);
    }

    /**
     * 订单付款完成，发送手机短信
     * @param Event $event
     * @return bool
     */
    public function onSendPaymentOrderSms(Event $event)
    {
        $data = $this->checkSendSms($event);
        if(!$data) return false;

        $sendArray  = $data['sendArray'];

        return PhoneMessage::sendOrderSms(['phoneAreaCode' => $data['userInfo']->getAreaCode(), 'phone' => $data['userInfo']->getUserPhone(), 'contentArray' => $sendArray, 'templateCode' => 'paymentOrder']);
    }

    /**
     * 后台订单发货完成，发送手机短信
     * @param Event $event
     * @return bool
     */
    public function onSendShipOrderSms(Event $event)
    {
        $data = $this->checkSendSms($event);
        if(!$data) return false;

        $sendArray  = $data['sendArray'];
        if($data['orderInfo']->getDeliveryMode() == 2) {//单独配送
            $deliveryName = [];
            $expressNumber= [];
            $orderGoods = $data['orderInfo']->getOrderGoods();
            foreach ($orderGoods as $key => $goodsValue) {
                if (!empty($goodsValue->getDeliveryName()))     $deliveryName[]    = $goodsValue->getDeliveryName();
                if (!empty($goodsValue->getExpressNumber()))    $expressNumber[]   = $goodsValue->getExpressNumber();
            }
            $sendArray['deliveryName']  = empty($deliveryName)  ? $this->translator->translate('无信息') : implode('|', $deliveryName);
            $sendArray['expressNumber'] = empty($expressNumber) ? $this->translator->translate('无单号') : implode('|', $expressNumber);
        } else {//统一配送
            $sendArray['deliveryName']  = empty($data['orderInfo']->getDeliveryName())  ? $this->translator->translate('无信息') : $data['orderInfo']->getDeliveryName();
            $sendArray['expressNumber'] = empty($data['orderInfo']->getExpressNumber()) ? $this->translator->translate('无单号') : $data['orderInfo']->getExpressNumber();
        }

        return PhoneMessage::sendOrderSms(['phoneAreaCode' => $data['userInfo']->getAreaCode(), 'phone' => $data['userInfo']->getUserPhone(), 'contentArray' => $sendArray, 'templateCode' => 'shipOrder']);
    }

    /**
     * 订单收货完成，发送手机短信
     * @param Event $event
     * @return bool
     */
    public function onSendReceiptOrderSms(Event $event)
    {
        $data = $this->checkSendSms($event);
        if(!$data) return false;

        $sendArray  = $data['sendArray'];
        if($data['orderInfo']->getDeliveryMode() == 2) {//单独配送
            $deliveryName = [];
            $expressNumber= [];
            $orderGoods = $data['orderInfo']->getOrderGoods();
            foreach ($orderGoods as $key => $goodsValue) {
                $deliveryName[]    = $goodsValue->getDeliveryName();
                $expressNumber[]   = $goodsValue->getExpressNumber();
            }
            $sendArray['deliveryName']  = empty($deliveryName)  ? $this->translator->translate('无信息') : implode('|', $deliveryName);
            $sendArray['expressNumber'] = empty($expressNumber) ? $this->translator->translate('无单号') : implode('|', $expressNumber);
        } else {//统一配送
            $sendArray['deliveryName']  = empty($data['orderInfo']->getDeliveryName())  ? $this->translator->translate('无信息') : $data['orderInfo']->getDeliveryName();
            $sendArray['expressNumber'] = empty($data['orderInfo']->getExpressNumber()) ? $this->translator->translate('无单号') : $data['orderInfo']->getExpressNumber();
        }

        return PhoneMessage::sendOrderSms(['phoneAreaCode' => $data['userInfo']->getAreaCode(), 'phone' => $data['userInfo']->getUserPhone(), 'contentArray' => $sendArray, 'templateCode' => 'receiptOrder']);
    }

    /**
     * 订单取消完成，发送手机短信
     * @param Event $event
     * @return bool
     */
    public function onSendCancelOrderSms(Event $event)
    {
        $data = $this->checkSendSms($event);
        if(!$data) return false;

        $sendArray  = $data['sendArray'];

        return PhoneMessage::sendOrderSms(['phoneAreaCode' => $data['userInfo']->getAreaCode(), 'phone' => $data['userInfo']->getUserPhone(), 'contentArray' => $sendArray, 'templateCode' => 'cancelOrder']);
    }

    /**
     * 检查短信信息
     * @param $event
     * @return array|bool
     */
    private function checkSendSms($event)
    {
        $orderInfo = $event->getParam('orderInfo');
        $shopConfig= Common::readConfigFile('config');

        if($shopConfig['sms']['sms_state'] != 1) return false;

        $userInfo = $this->entityManager->getRepository(User::class)->findOneBy(['userId' => $orderInfo->getUserId()]);
        if($userInfo == null || empty($userInfo->getUserPhone())) return false;

        $sendArray = [];
        $sendArray['buyName']   = $orderInfo->getUserName();
        $sendArray['orderSn']   = $orderInfo->getOrderSn();
        $sendArray['orderTotal']= $orderInfo->getCurrencySymbol().$orderInfo->getOrderAmount();

        return ['shopConfig' => $shopConfig, 'orderInfo' => $orderInfo, 'userInfo' => $userInfo, 'sendArray' => $sendArray];
    }
}